package com.mxx.common.generator;

import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.mxx.common.conv.JsonUtil;
import lombok.SneakyThrows;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.FileWriter;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

public class EntityWriter {

    private static Template template;

    public static void loadDefault() {
        Properties p = new Properties();
        p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        p.setProperty("resource.loader.file.path", "");
        p.setProperty("UTF-8", ConstVal.UTF8);
        p.setProperty("resource.default_encoding", ConstVal.UTF8);
        p.setProperty("file.resource.loader.unicode", "true");
        VelocityEngine engine = new VelocityEngine(p);
        template = engine.getTemplate("java.vm", ConstVal.UTF8);
    }

    @SneakyThrows
    public static void writer(EntityInfo entityInfo, String fieldName) {
        Objects.requireNonNull(template);
        Map<String, Object> map = JsonUtil.toJSON(entityInfo);
        FileWriter fileWriter = new FileWriter(fieldName);
        template.merge(new VelocityContext(map), fileWriter);
        fileWriter.close();

    }
}
